package com.alchemystar.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * server端采用最简单的单循环处理socket方案
 */
public class TimeServer {

    public static void main(String[] args) throws Exception {
        int port = 8888;
        ServerSocket server = new ServerSocket(port);
        while (true) {
            try {
                // 从tcp内核队列中拿到一个已经三次握手成功的连接
                Socket socket = server.accept();
                // 从连接中获取client端发送的命令
                serverGetCommand(socket);
                serverSendResponse(socket);
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void serverGetCommand(Socket socket) throws IOException {
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = socket.getInputStream();
        while ((len = inputStream.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len, "UTF-8"));
        }
        System.out.println("get message from client: " + sb);
        // 这边inputShutdown才能让client端那边readbyte -1
        socket.shutdownInput();
    }

    public static void serverSendResponse(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        String timeMessage = "Now time is " + new Date() + "\n";
        outputStream.write(timeMessage.getBytes("UTF-8"));
        outputStream.flush();
        // 这边需要shutdown,才能让server端的read(bytes)=-1
        socket.shutdownOutput();
    }

}
